import requests
from typing import Optional


class TelegramBot:
    def __init__(self, token: str, default_chat_id: Optional[str] = None):
        self.token = token
        self.default_chat_id = default_chat_id
        self.base_url = f"https://api.telegram.org/bot{token}"

    def send_message(self,
                     message: str,
                     chat_id: Optional[str] = None,
                     parse_mode: str = 'HTML',
                     disable_web_page_preview: bool = True) -> bool:
        """
        发送消息到 Telegram

        :param message: 消息内容
        :param chat_id: 聊天ID，如果为None则使用默认ID
        :param parse_mode: 解析模式 ('HTML' 或 'Markdown')
        :param disable_web_page_preview: 是否禁用链接预览
        :return: 是否发送成功
        """
        if chat_id is None:
            if self.default_chat_id is None:
                raise ValueError("未提供 chat_id 且没有设置默认 chat_id")
            chat_id = self.default_chat_id

        url = f"{self.base_url}/sendMessage"

        payload = {
            'chat_id': chat_id,
            'text': message,
            'parse_mode': parse_mode,
            'disable_web_page_preview': disable_web_page_preview
        }

        try:
            response = requests.post(url, data=payload, timeout=10)
            response.raise_for_status()
            print("✅ 消息发送成功！")
            return True
        except requests.exceptions.RequestException as e:
            print(f"❌ 消息发送失败: {e}")
            return False

    def send_formatted_message(self,
                               title: str,
                               content: str,
                               chat_id: Optional[str] = None) -> bool:
        """
        发送格式化的消息
        """
        formatted_message = f"""
<b>{title}</b>

{content}

<code>发送时间: {self.get_current_time()}</code>
        """.strip()

        return self.send_message(formatted_message, chat_id)

    @staticmethod
    def get_current_time():
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


# 使用示例
if __name__ == "__main__":
    # 初始化机器人
    bot = TelegramBot(
        # token="8375300563:AAG88IfT6BWWbTABtRS679aSDVwD2NTgCkk",
        # token="8360527491:AAGhw2KSs-Ctfnzbregjj8vSHxBCaHGsd_M",
        token= "8405992519:AAF6ydOzq1miJa0spNM4x2zB-SgRB0CObzg",
        # default_chat_id="7119771577",
        default_chat_id="-1003171557001"

    )

    # 发送简单消息
    # bot.send_message("你好,我是苏丽")

    # # 发送格式化消息
    bot.send_formatted_message(
        title="测试请忽略",
        content="BTC 价格已达到 $50,000"
    )
    #
    # # 发送给特定的聊天ID
    # bot.send_message(
    #     message="这是发送给特定聊天ID的消息",
    #     chat_id="另一个聊天ID"
    # )